package com.ant.collect.controller;

import com.ant.collect.common.ResultVo;
import com.ant.collect.dto.CensusDto;
import com.ant.collect.service.IEnvironmentalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/filer")
@Api(tags = "文件上传接口")
public class FilerController {

    @Value("${file.upload-path}")
    private String uploadPath;
    @Value("${fileUrl.url}")
    private String fileUrl;

    @Autowired
    IEnvironmentalService environmentalService;

    @ApiOperation(value = "上传图片")
    @PostMapping("/singleUpload")
    public ResultVo fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return ResultVo.success("请选择文件");
        }
        String str = savaFile(file);
        if (str != null) {
            String url=fileUrl + "/" + str;
            return ResultVo.success("上传成功", url);
        } else {
            return ResultVo.fail("上传失败");
        }
    }

    /**
     * 单个文件上传
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String savaFile(MultipartFile multipartFile) throws IOException {
        try {
            // 上传目录地址
            String uploadDir = uploadPath;
            // 如果目录不存在，自动创建文件夹
            System.out.println("uploadDir:" + uploadDir);
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            //获取上传文件的后缀名
            String suffixName =
                    multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."));
            // 获取上传文件的名称
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String filename = uuid + suffixName;
            File newFile = new File(uploadDir + filename);
            // 完成文件上传
            try {
                multipartFile.transferTo(newFile);
                return filename;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @ApiOperation(value = "上传图片")
    @GetMapping("/census")
    public ResultVo census(CensusDto dto) throws Exception {
        Map<String, Object> census = environmentalService.census(dto);
        return ResultVo.success("上传成功", census);
    }
}
